package com.lxq.market.servlet;

import com.google.gson.JsonObject;
import com.lxq.market.model.User;
import com.lxq.market.service.UserService;
import com.lxq.market.util.Defined;
import com.lxq.market.util.SessionSignIn;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/user/alter_user_info")
@MultipartConfig
public class AlterUserInfo extends HttpServlet {

    SessionSignIn signIn=SessionSignIn.getInstance();
    UserService userService=UserService.getInstance();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = signIn.find(req.getSession().getId());
        String userName = req.getParameter("user_name");
        String userPw = req.getParameter("user_pw");
        Part userAvatar = req.getPart("user_avatar");
        if (userName!=null)user.setUserName(userName);
        if (userPw!=null)user.setUserPassword(userPw);
        if (userAvatar!=null) {
            userAvatar.write(Defined.userAvatar+"/"+user.getUserAccount()+".gif");
            user.setUserAvatar(Defined.urlMap+Defined.userAvatarDir+"/"+user.getUserAccount()+".gif");
        }
        resp.setContentType("application/json;charset=utf-8");
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("result", userService.updateUserInfo(user));
        resp.getOutputStream().write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
    }
}
